<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 1] 1.2 A Simple Example</TITLE>
<META NAME="author" CONTENT="David Flanagan">
<META NAME="date" CONTENT="Thu Jul 31 15:45:44 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Java in a Nutshell">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java in a Nutshell" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch01_01.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 1<br>Getting Started with Java</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch02_01.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JNUT2-CH-1-SECT-2">1.2 A Simple Example</A></h2>

<P CLASS=para>
By now you should have a pretty good idea of why Java is
such an interesting language.  So we'll stop talking about
abstract concepts and look at some concrete Java code.
Before we look at an interesting applet, however, we are
going to pay tribute to that ubiquitous favorite, "Hello
World."

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-1-SECT-2.1">Hello World</A></h3>

<P CLASS=para>
<A HREF="ch01_02.htm#JNUT2-CH-1-EX-1">Example 1.1</A>
shows the simplest possible Java program: "Hello World."

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-1-EX-1">Example 1.1: Hello World</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
This program, like every Java program, consists of a public
class definition.  The class contains a method named
<tt CLASS=literal>main()</tt>, which is the main entry point for all Java
applications--that is, the point at which the interpreter
starts executing the program.  The body of <tt CLASS=literal>main()</tt>
consists of only a single line, which prints out the
message:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
Hello World!
</PRE>
</DIV>

<P CLASS=para>
This program must be saved in a file with the same name as
the public class plus a <I CLASS=emphasis>.java</I> extension.  To compile
it, you would use <I CLASS=emphasis>javac</I>:
[1]

<blockquote class=footnote>
<P CLASS=para>[1] 
Assuming you're using Sun's Java Development Kit (JDK).  If
you're using a Java development environment from some other
vendor, follow your vendor's instructions.
</blockquote>
<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
% javac HelloWorld.java
</PRE>
</DIV>

<P CLASS=para>
This command produces the <I CLASS=emphasis>HelloWorld.class</I> file in the
current directory.  To run the program, you use the Java
interpreter, <I CLASS=emphasis>java</I>:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
% java HelloWorld
</PRE>
</DIV>

<P CLASS=para>
Note that when you invoke the interpreter, you do not supply
the <I CLASS=emphasis>.class</I> extension for the file you want to run.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-1-SECT-2.2">A Scribble Applet</A></h3>

<P CLASS=para>
<A NAME="APPLETS"></A><A HREF="ch01_02.htm#JNUT2-CH-1-EX-2">Example 1.2</A>
shows a less trivial Java program.  This program is an
applet, rather than a standalone Java application like the
"Hello World" program above.  Because this example is an
applet, it has a different structure than a standalone
application; notably, it does not have a <tt CLASS=literal>main()</tt>
method.  Like all applets, this one runs inside an applet
viewer or Web browser, and lets the user draw (or scribble)
with the mouse, as illustrated in <A HREF="ch01_02.htm#JNUT2-CH-1-FIG-1">Figure 1.1</A>.

<DIV CLASS=figure>
<h4 CLASS=figure><A CLASS="TITLE" NAME="JNUT2-CH-1-FIG-1">Figure 1.1: A Java applet running in a Web browser</A></h4>


<p>
<img align=middle src="./figs/jn2_0101.gif" alt="[Graphic: Figure 1-1]" width=464 height=443 border=0>

</DIV>

<P CLASS=para>
One of the major changes between Java 1.0 and Java 1.1 is in
the way that Java programs are notified of "events", such as
mouse motion.
<A HREF="ch01_02.htm#JNUT2-CH-1-EX-2">Example 1.2</A>
uses the Java 1.0 event model rather than the preferred Java
1.1 event model.  This is because the current generation of
Web browsers (as this is written) still use Java 1.0.  In
order for this applet to be widely usable, it is coded with
the old, "deprecated" event model.
[2]

<blockquote class=footnote>
<P CLASS=para>[2] 
If you are interested in updating this program to use Java 1.1,
see <A HREF="ch07_01.htm">Chapter 7, <i>Events</i></A> for information on how to use the new 1.1 event model.
In addition, you need
to change the call to <tt CLASS=literal>bounds()</tt> in the <tt CLASS=literal>action()</tt>
method to a call to <tt CLASS=literal>getBounds()</tt>, if you want to avoid
a compilation warning about using a deprecated method.
</blockquote>
<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-1-EX-2">Example 1.2: A Java Applet</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
import java.applet.*;
import java.awt.*;
public class Scribble extends Applet {
  private int last_x, last_y;                // Store the last mouse position.
  private Color current_color = Color.black; // Store the current color.
  private Button clear_button;               // The clear button.
  private Choice color_choices;              // The color dropdown list.
  // This method is called to initialize the applet.
  // Applets don't have a main() method.
  public void init() {
    // Set the background color.
    this.setBackground(Color.white);
    // Create a button and add it to the applet.  Set the button's colors.
    clear_button = new Button("Clear");
    clear_button.setForeground(Color.black);
    clear_button.setBackground(Color.lightGray);
    this.add(clear_button);
    // Create a menu of colors and add it to the applet.
    // Also set the menu's colors and add a label.
    color_choices = new Choice();
    color_choices.addItem("black");
    color_choices.addItem("red");
    color_choices.addItem("yellow");
    color_choices.addItem("green");
    color_choices.setForeground(Color.black);
    color_choices.setBackground(Color.lightGray);
    this.add(new Label("Color: "));
    this.add(color_choices);
  }
  // This method is called when the user clicks the mouse to start a scribble.
  public boolean mouseDown(Event e, int x, int y)
  {
    last_x = x; last_y = y;
    return true;
  }
  // This method is called when the user drags the mouse.
  public boolean mouseDrag(Event e, int x, int y)
  {
    Graphics g = this.getGraphics();
    g.setColor(current_color);
    g.drawLine(last_x, last_y, x, y);
    last_x = x;
    last_y = y;
    return true;
  }
  // This method is called when the user clicks the button or chooses a color.
  public boolean action(Event event, Object arg) {
    // If the Clear button was clicked on, handle it.
    if (event.target == clear_button) {
      Graphics g = this.getGraphics();
      Rectangle r = this.bounds();
      g.setColor(this.getBackground());
      g.fillRect(r.x, r.y, r.width, r.height);
      return true;
    }
    // Otherwise if a color was chosen, handle that.
    else if (event.target == color_choices) {
      if (arg.equals("black")) current_color = Color.black;
      else if (arg.equals("red")) current_color = Color.red;
      else if (arg.equals("yellow")) current_color = Color.yellow;
      else if (arg.equals("green")) current_color = Color.green;
      return true;
    }
    // Otherwise, let the superclass handle it.
    else return super.action(event, arg);
  }
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
Don't expect to be able to understand the entire applet at
this point. It is here to give you the flavor of the
language. In <A HREF="ch02_01.htm">Chapter 2, <i>How Java Differs from C</i></A> and
<A HREF="ch03_01.htm">Chapter 3, <i>Classes and Objects in Java</i></A> we'll explain
the language constructs you need to understand the example.
Then, in <A HREF="ch06_01.htm">Chapter 6, <i>Applets</i></A> and <A HREF="ch07_01.htm">Chapter 7, <i>Events</i></A>
we'll explain the applet and event-handling
concepts used in this example.

<P CLASS=para>
The first thing you should notice when browsing through the
code is that it looks reassuringly like C and C++.  The
<tt CLASS=literal>if</tt> and <tt CLASS=literal>return</tt> statements are familiar.
Assignment of values to variables uses the expected syntax.
Procedures (called "methods" in Java) are recognizable as
such.

<P CLASS=para>
The second thing to notice is the object-oriented nature of
the code.  As you can see at the top of the example, the
program consists of the definition of a public class.  The
name of the class we are defining is <tt CLASS=literal>Scribble</tt>; it is
an extension, or subclass, of the <tt CLASS=literal>Applet</tt> class.
(The full name of the <tt CLASS=literal>Applet</tt> class is
<tt CLASS=literal>java.applet.Applet</tt>.  One of the <tt CLASS=literal>import</tt>
statements at the top of the example allows us to refer to
<tt CLASS=literal>Applet</tt> by this shorter name.)

<P CLASS=para>
Classes are said to "encapsulate" data and methods.  As you
can see, our <tt CLASS=literal>Scribble</tt> class contains both variable
and method declarations.  The methods are actually defined
inside of the class.  The methods of a class are often
invoked through an instance of the class.  Thus you see
lines like:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
color_choices.addItem("black");
</PRE>
</DIV>

<P CLASS=para>
This line of code invokes the <tt CLASS=literal>addItem()</tt> method of
the object referred to by the <tt CLASS=literal>color_choices</tt>
variable.  If you're a C programmer, but not a C++
programmer, this syntax may take a little getting used to.
We'll see lots more of it in Chapters 2 and 3.  Note that
<tt CLASS=literal>this</tt> is a keyword, not a variable name.  It refers
to the current object; in this example, it refers to the
<tt CLASS=literal>Scribble</tt> object.

<P CLASS=para>
The <tt CLASS=literal>init()</tt> method of an applet is called by the Web
browser or applet viewer when it is starting the applet up.
In our example, this method creates a <b>Clear</b> button and
a menu of color choices, and then adds these GUI components
to the applet.

<P CLASS=para>
The <tt CLASS=literal>mouseDown()</tt> and <tt CLASS=literal>mouseDrag()</tt> methods are
called when the user clicks and drags the mouse.  These are
the methods that are responsible for drawing lines as the
user scribbles.  The <tt CLASS=literal>action()</tt> method is invoked when
the user clicks on the <b>Clear</b> button or selects 
a color from the menu of colors.  The body of the method determines
which of these two "events" has occurred and handles the
event appropriately.  Recall that these methods are
part of the Java 1.0 event model.  <A HREF="ch07_01.htm">Chapter 7, <i>Events</i></A> explains this
model and also explains the Java 1.1 event model that
replaces it.

<P CLASS=para>
To compile this example, you'd save it in a file named
<I CLASS=emphasis>Scribble.java</I> and use <I CLASS=emphasis>javac</I>:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
% javac Scribble.java
</PRE>
</DIV>

<P CLASS=para>
This example is an applet, not a standalone program like our
"Hello World" example.  It does not have a <tt CLASS=literal>main()</tt>
method, and therefore cannot be run directly by the Java
interpreter.  Instead, we must reference it in an HTML file
and run the applet in an applet viewer or Web browser.  It
is the applet viewer or Web browser that loads the applet
class into its running Java interpreter and invokes the
various methods of the applet at the appropriate times.  To
include the applet in a Web page, we'd use an HTML fragment
like the following:

<DIV CLASS=screen>
<P>
<PRE>
&lt;APPLET code="Scribble.class" width=500 height=300&gt;
&lt;/APPLET&gt;
</PRE>
</DIV>

<P CLASS=para>
<A HREF="ch01_02.htm#JNUT2-CH-1-EX-3">Example 1.3</A>
shows a complete HTML file that we might use to display the
applet.  <A HREF="ch15_01.htm">Chapter 15, <i>Java-Related HTML Tags</i></A> explains
the HTML syntax for applets in full detail.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-1-EX-3">Example 1.3: An HTML File that Contains an Applet</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
&lt;HTML&gt;
&lt;HEAD&gt;
&lt;TITLE&gt;The Scribble Applet&lt;/TITLE&gt;
&lt;/HEAD&gt;
&lt;BODY&gt;
Please scribble away in the applet below.
&lt;P&gt;
&lt;APPLET code="Scribble.class" width=500 height=300&gt;
Your browser does not support Java, or Java is not enabled. Sorry!
&lt;/APPLET&gt;
&lt;/BODY&gt;
&lt;/HTML&gt;
</PRE>
</DIV>

</DIV>

<P CLASS=para>
Suppose we save this example HTML file as
<I CLASS=emphasis>Scribble.html</I>.  Then to run this applet, you could use
Sun's <I CLASS=emphasis>appletviewer</I> command like this:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
% appletviewer Scribble.html
</PRE>
</DIV>

<P CLASS=para>
You could also display the applet by viewing the
<I CLASS=emphasis>Scribble.html</I> file in your Web browser, if your
browser supports Java applets.
<A HREF="ch01_02.htm#JNUT2-CH-1-FIG-1">Figure 1.1</A>
showed the <tt CLASS=literal>Scribble</tt> applet running in Netscape Navigator.

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch01_01.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch02_01.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Why Is Java Interesting?</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>How Java Differs from C</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
